<template>
  <div class="knowledge-base-container">
    <el-card shadow="hover">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>知识库管理</span>
          <el-space :size="8" wrap>
            <el-button type="info" @click="handleInitializeVector" :loading="isInitializing">
              <el-icon><Refresh /></el-icon>
              初始化向量数据库
            </el-button>
            <el-button type="primary" @click="checkQdrantCount" :loading="qdrantLoading">
              向量数量
            </el-button>
            <el-button type="primary" plain @click="showQdrantCollectionInfo" :loading="qdrantLoading">
              集合信息
            </el-button>
            <el-button type="primary" plain @click="showQdrantSamples" :loading="qdrantLoading">
              查看示例(5)
            </el-button>
            <el-button type="success" @click="showRAGFlowSyncDialog">
              <el-icon><Connection /></el-icon>
              同步RAGflow知识库
            </el-button>
            <el-button type="warning" @click="handleSyncToVector" :loading="isSyncing">
              <el-icon><Refresh /></el-icon>
              同步到向量数据库
            </el-button>
            <el-button type="success" plain @click="handleSyncSelectedToVector" :loading="isSyncing">
              <el-icon><Refresh /></el-icon>
              同步选中
            </el-button>
            <el-button type="primary" @click="showAddDialog">添加知识</el-button>
            <el-button type="info" plain @click="goToPersonalMemory">
              <el-icon><Memo /></el-icon>
              个人记忆管理
            </el-button>
          </el-space>
        </div>
      </template>
      
      <el-form :inline="true">
        <el-form-item label="关键词">
          <el-input v-model="state.filters.keyword" placeholder="标题/内容/关键词..." style="width:260px" />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="state.filters.category" placeholder="全部" clearable style="width:160px">
            <el-option v-for="cat in categories" :key="cat.id" :label="getCategoryDisplayName(cat.name)" :value="cat.name" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <el-table :data="state.tableData" v-loading="state.loading" row-key="id" border @selection-change="onSelectionChange">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="{ row }">
            {{ getCategoryDisplayName(row.category) }}
          </template>
        </el-table-column>
        <el-table-column prop="keywords" label="关键词" min-width="150" show-overflow-tooltip />
        <el-table-column prop="source" label="来源" width="120" />
        <el-table-column prop="priority" label="优先级" width="80">
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)" size="small">
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="accessCount" label="访问次数" width="100" />
        <el-table-column prop="lastUpdated" label="更新时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewKnowledge(row)">查看</el-button>
            <el-button size="small" type="primary" @click="editKnowledge(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteKnowledge(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-model:current-page="state.params.page"
        v-model:page-size="state.params.pageSize"
        :total="state.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleQuery"
        @current-change="handleQuery"
        style="margin-top: 20px; text-align: right;"
      />
    </el-card>

    <!-- 添加/编辑知识对话框 -->
    <el-dialog
      v-model="knowledgeDialogVisible"
      :title="isEdit ? '编辑知识' : '添加知识'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form :model="knowledgeForm" label-width="100px">
        <el-form-item label="标题" required>
          <el-input v-model="knowledgeForm.title" placeholder="请输入知识标题" />
        </el-form-item>
        <el-form-item label="分类" required>
          <el-select v-model="knowledgeForm.category" placeholder="请选择分类">
            <el-option v-for="cat in categories" :key="cat.id" :label="getCategoryDisplayName(cat.name)" :value="cat.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model="knowledgeForm.keywords" placeholder="请输入关键词，多个用逗号分隔" />
        </el-form-item>
        <el-form-item label="内容" required>
          <el-input 
            v-model="knowledgeForm.content" 
            type="textarea" 
            :rows="8"
            placeholder="请输入知识内容"
          />
        </el-form-item>
        <el-form-item label="来源">
          <el-input v-model="knowledgeForm.source" placeholder="请输入知识来源" />
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="knowledgeForm.priority" placeholder="请选择优先级">
            <el-option label="低" :value="1" />
            <el-option label="中" :value="2" />
            <el-option label="高" :value="3" />
            <el-option label="紧急" :value="4" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="knowledgeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveKnowledge" :loading="isSaving">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 知识详情对话框 -->
    <el-dialog
      v-model="knowledgeDetailVisible"
      :title="`知识详情 - ${currentKnowledge?.title}`"
      width="600px"
    >
      <div v-if="currentKnowledge" class="knowledge-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="标题">{{ currentKnowledge.title }}</el-descriptions-item>
          <el-descriptions-item label="分类">{{ getCategoryDisplayName(currentKnowledge.category) }}</el-descriptions-item>
          <el-descriptions-item label="关键词">{{ currentKnowledge.keywords }}</el-descriptions-item>
          <el-descriptions-item label="来源">{{ currentKnowledge.source }}</el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityType(currentKnowledge.priority)">
              {{ getPriorityText(currentKnowledge.priority) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="访问次数">{{ currentKnowledge.accessCount }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentKnowledge.createTime }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ currentKnowledge.lastUpdated }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider>内容</el-divider>
        <div class="knowledge-content">
          {{ currentKnowledge.content }}
        </div>
      </div>
      <template #footer>
        <el-button @click="knowledgeDetailVisible = false">关闭</el-button>
        <el-button type="primary" @click="editKnowledge(currentKnowledge)">编辑</el-button>
      </template>
    </el-dialog>

    <!-- 向量同步结果对话框 -->
    <el-dialog
      v-model="syncResultVisible"
      title="向量同步结果"
      width="700px"
      :close-on-click-modal="false"
    >
      <div v-if="syncResult" class="sync-result">
        <el-alert
          :type="syncResult.failed === 0 ? 'success' : 'warning'"
          :closable="false"
          show-icon
        >
          <template #title>
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <span>同步完成</span>
              <div style="font-size: 16px;">
                <span style="color: #67C23A; margin-right: 20px;">成功: {{ syncResult.success }}</span>
                <span style="color: #F56C6C;">失败: {{ syncResult.failed }}</span>
              </div>
            </div>
          </template>
        </el-alert>
        
        <el-divider>统计信息</el-divider>
        <el-descriptions :column="2" border style="margin-top: 15px;">
          <el-descriptions-item label="总计" :span="2">
            <el-tag type="info" size="large">{{ syncResult.total }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="成功">
            <el-tag type="success" size="large">{{ syncResult.success }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="失败">
            <el-tag type="danger" size="large">{{ syncResult.failed }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <div v-if="syncResult.errors && syncResult.errors.length > 0" style="margin-top: 20px;">
          <el-divider>错误信息</el-divider>
          <el-scrollbar height="200px">
            <div
              v-for="(error, index) in syncResult.errors"
              :key="index"
              style="margin-bottom: 8px; padding: 8px; background: #FEF0F0; border-left: 3px solid #F56C6C; border-radius: 4px;"
            >
              <el-text type="danger" size="small">{{ error }}</el-text>
            </div>
          </el-scrollbar>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="syncResultVisible = false">确定</el-button>
      </template>
    </el-dialog>

    <!-- Qdrant 集合信息对话框 -->
    <el-dialog
      v-model="qdrantCollectionDialogVisible"
      title="Qdrant 集合信息"
      width="700px"
    >
      <el-scrollbar height="420px">
        <pre style="white-space: pre-wrap; word-break: break-all;">
{{ qdrantCollectionJson }}
        </pre>
      </el-scrollbar>
      <template #footer>
        <el-button @click="qdrantCollectionDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- Qdrant 示例点对话框 -->
    <el-dialog
      v-model="qdrantSamplesDialogVisible"
      title="Qdrant 示例点 (前5条)"
      width="800px"
    >
      <el-scrollbar height="420px">
        <pre style="white-space: pre-wrap; word-break: break-all;">
{{ qdrantSamplesJson }}
        </pre>
      </el-scrollbar>
      <template #footer>
        <el-button @click="qdrantSamplesDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="批量导入知识"
      width="600px"
    >
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :on-change="handleFileChange"
        accept=".json,.csv,.txt"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 JSON、CSV、TXT 格式文件
          </div>
        </template>
      </el-upload>
      
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleImport" :loading="isImporting">
          导入
        </el-button>
      </template>
    </el-dialog>

    <!-- RAGflow同步对话框 -->
    <el-dialog
      v-model="ragFlowSyncDialogVisible"
      title="同步RAGflow知识库"
      width="900px"
      :close-on-click-modal="false"
    >
      <el-alert
        type="info"
        :closable="false"
        show-icon
        style="margin-bottom: 20px;"
      >
        <template #title>
          <div>
            <p>从RAGflow知识库同步知识到本地数据库和向量数据库</p>
            <p style="margin-top: 5px; font-size: 12px; color: #909399;">
              选择要同步的知识库，系统将获取所有已解析的知识块并同步到本地
            </p>
          </div>
        </template>
      </el-alert>

      <div style="margin-bottom: 15px; text-align: right;">
        <el-button @click="refreshRAGFlowKnowledgeBases" :loading="ragFlowLoading">
          <el-icon><Refresh /></el-icon>
          刷新知识库列表
        </el-button>
      </div>

      <el-table :data="ragFlowKnowledgeBases" v-loading="ragFlowLoading" border>
        <el-table-column prop="name" label="知识库名称" min-width="200" />
        <el-table-column prop="description" label="描述" min-width="250" show-overflow-tooltip />
        <el-table-column prop="id" label="知识库ID" width="280" show-overflow-tooltip />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="syncSingleKnowledgeBase(row.id)"
              :loading="ragFlowSyncing"
            >
              同步
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="ragFlowKnowledgeBases.length === 0 && !ragFlowLoading" style="text-align: center; padding: 40px; color: #909399;">
        <el-empty description="暂无知识库数据">
          <el-button type="primary" @click="refreshRAGFlowKnowledgeBases">刷新列表</el-button>
        </el-empty>
      </div>

      <template #footer>
        <el-button @click="ragFlowSyncDialogVisible = false">关闭</el-button>
        <el-button
          type="success"
          @click="syncAllKnowledgeBases"
          :loading="ragFlowSyncing"
          :disabled="ragFlowKnowledgeBases.length === 0"
        >
          同步所有知识库
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup name="KnowledgeBase">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { UploadFilled, Refresh, Connection, Memo } from '@element-plus/icons-vue';
import { useKnowledgeBaseApi, useRAGFlowSyncApi, type KnowledgeBase, type KnowledgeCategory, type SyncResult, type RAGFlowKnowledgeBase } from '/@/api/knowledgeBase';

const router = useRouter();

const knowledgeBaseApi = useKnowledgeBaseApi();
const ragFlowSyncApi = useRAGFlowSyncApi();

const state = reactive({
  loading: false,
  tableData: [] as KnowledgeBase[],
  total: 0,
  params: { page: 1, pageSize: 20 },
  filters: { keyword: '', category: '' }
});

const categories = ref<KnowledgeCategory[]>([]);
const knowledgeDialogVisible = ref(false);
const knowledgeDetailVisible = ref(false);
const importDialogVisible = ref(false);
const syncResultVisible = ref(false);
const isEdit = ref(false);
const isSaving = ref(false);
const isImporting = ref(false);
const isSyncing = ref(false);
const isInitializing = ref(false);
const currentKnowledge = ref<KnowledgeBase | null>(null);
const uploadRef = ref();
const syncResult = ref<SyncResult | null>(null);
  const selectedRows = ref<KnowledgeBase[]>([]);
const ragFlowSyncDialogVisible = ref(false);
const ragFlowKnowledgeBases = ref<RAGFlowKnowledgeBase[]>([]);
const ragFlowLoading = ref(false);
const ragFlowSyncing = ref(false);
const qdrantLoading = ref(false);
const qdrantCollectionDialogVisible = ref(false);
const qdrantSamplesDialogVisible = ref(false);
const qdrantCollectionJson = ref('');
const qdrantSamplesJson = ref('');

const knowledgeForm = reactive({
  id: 0,
  title: '',
  category: '',
  keywords: '',
  content: '',
  source: '',
  priority: 2
});

// 查询知识库
const handleQuery = async () => {
  state.loading = true;
  try {
    const params = { ...state.params, ...state.filters };
    const res = await knowledgeBaseApi.getPage(params);
    state.tableData = res.data?.result?.items || [];
    state.total = res.data?.result?.total || 0;
  } finally {
    state.loading = false;
  }
};

// 重置筛选条件
const resetFilters = () => {
  state.filters = { keyword: '', category: '' };
  handleQuery();
};

// 初始化/重建 Qdrant 集合（使用配置维度）
const handleInitializeVector = async () => {
  try {
    await ElMessageBox.confirm('将按当前配置维度创建/重建 Qdrant 集合，可能会清空已有向量。是否继续？', '初始化向量数据库', {
      confirmButtonText: '继续',
      cancelButtonText: '取消',
      type: 'warning',
    });
  } catch {
    return;
  }

  isInitializing.value = true;
  try {
    await knowledgeBaseApi.initializeQdrantCollection();
    ElMessage.success('向量数据库初始化成功');
  } catch (e) {
    console.error(e);
    ElMessage.error('初始化失败，请查看后端日志');
  } finally {
    isInitializing.value = false;
  }
};

// 查看知识详情
const viewKnowledge = (row: KnowledgeBase) => {
  currentKnowledge.value = row;
  knowledgeDetailVisible.value = true;
};

// 编辑知识
const editKnowledge = (row: KnowledgeBase) => {
  isEdit.value = true;
  Object.assign(knowledgeForm, row);
  knowledgeDialogVisible.value = true;
};

// 添加知识
const showAddDialog = () => {
  isEdit.value = false;
  Object.assign(knowledgeForm, {
    id: 0,
    title: '',
    category: '',
    keywords: '',
    content: '',
    source: '',
    priority: 2
  });
  knowledgeDialogVisible.value = true;
};

// 保存知识
const saveKnowledge = async () => {
  if (!knowledgeForm.title.trim() || !knowledgeForm.content.trim()) {
    ElMessage.warning('请填写完整的知识信息');
    return;
  }

  isSaving.value = true;
  try {
    if (isEdit.value) {
      await knowledgeBaseApi.update(knowledgeForm);
      ElMessage.success('知识更新成功');
    } else {
      await knowledgeBaseApi.add(knowledgeForm);
      ElMessage.success('知识添加成功');
    }
    
    knowledgeDialogVisible.value = false;
    await handleQuery();
  } catch (error) {
    ElMessage.error('保存失败，请重试');
  } finally {
    isSaving.value = false;
  }
};

// 删除知识
const deleteKnowledge = async (row: KnowledgeBase) => {
  await ElMessageBox.confirm(`确认删除知识"${row.title}"吗？`, '删除确认', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  });
  
  try {
    await knowledgeBaseApi.delete(row.id);
    ElMessage.success('删除成功');
    await handleQuery();
  } catch (error) {
    ElMessage.error('删除失败，请重试');
  }
};

// 批量导入
const showImportDialog = () => {
  importDialogVisible.value = true;
};

const handleFileChange = (file: any) => {
  // 处理文件选择
};

const handleImport = async () => {
  // 实现批量导入逻辑
  ElMessage.info('批量导入功能开发中...');
};

// 分类管理
const showCategoryDialog = () => {
  ElMessage.info('分类管理功能开发中...');
};

// 同步到向量数据库
const handleSyncToVector = async () => {
  await ElMessageBox.confirm(
    '此操作将把所有现有知识库同步到向量数据库，可能需要几分钟时间。是否继续？',
    '确认同步',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      distinguishCancelAndClose: true
    }
  );

  isSyncing.value = true;
  try {
    const res = await knowledgeBaseApi.syncExistingKnowledgeToVector();
    syncResult.value = res.data?.result || null;
    syncResultVisible.value = true;
    
    if (syncResult.value && syncResult.value.failed === 0) {
      ElMessage.success(`同步成功！共处理 ${syncResult.value.total} 条知识`);
    } else if (syncResult.value) {
      ElMessage.warning(`同步完成，${syncResult.value.success} 条成功，${syncResult.value.failed} 条失败`);
    }
  } catch (error: any) {
    console.error('同步失败:', error);
    ElMessage.error(error?.message || '同步失败，请重试');
  } finally {
    isSyncing.value = false;
  }
};

// 同步选中到向量数据库
const handleSyncSelectedToVector = async () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请先勾选需要同步的知识');
    return;
  }
  try {
    await ElMessageBox.confirm(
      `将同步选中的 ${selectedRows.value.length} 条知识到向量数据库，是否继续？`,
      '确认同步',
      { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' }
    );
  } catch {
    return;
  }

  isSyncing.value = true;
  try {
    const ids = selectedRows.value.map(x => Number(x.id)).filter(Boolean);
    const res = await knowledgeBaseApi.syncExistingKnowledgeToVector({ ids });
    syncResult.value = res.data?.result || null;
    syncResultVisible.value = true;
    if (syncResult.value && syncResult.value.failed === 0) {
      ElMessage.success(`同步成功！共处理 ${syncResult.value.total} 条知识`);
    } else if (syncResult.value) {
      ElMessage.warning(`同步完成，${syncResult.value.success} 条成功，${syncResult.value.failed} 条失败`);
    }
  } catch (error: any) {
    console.error('同步失败:', error);
    ElMessage.error(error?.message || '同步失败，请重试');
  } finally {
    isSyncing.value = false;
  }
};

// 选择变化
const onSelectionChange = (rows: KnowledgeBase[]) => {
  selectedRows.value = rows || [];
};

// 获取优先级类型
const getPriorityType = (priority: number) => {
  const typeMap = { 1: 'info', 2: 'primary', 3: 'warning', 4: 'danger' };
  return typeMap[priority] || 'info';
};

// 获取优先级文本
const getPriorityText = (priority: number) => {
  const textMap = { 1: '低', 2: '中', 3: '高', 4: '紧急' };
  return textMap[priority] || '未知';
};

// 获取分类列表
const getCategories = async () => {
  try {
    const res = await knowledgeBaseApi.getCategories();
    categories.value = res.data?.result || [];
  } catch (error) {
    console.error('获取分类失败:', error);
  }
};

// 获取分类显示名称（英文代码转中文）
const getCategoryDisplayName = (categoryName: string): string => {
  const categoryMap: Record<string, string> = {
    // WMS系统相关分类
    'inventory_query': '库存查询',
    'order_query': '订单查询',
    'warehouse_operation': '仓库操作',
    'error_report': '错误报告',
    'system_help': '系统帮助',
    'inbound_management': '入库管理',
    'outbound_management': '出库管理',
    'purchase_management': '采购管理',
    'sales_management': '销售管理',
    'report_analysis': '报表分析',
    // 通用分类
    'product_knowledge': '产品知识',
    'customer_service': '客户服务',
    'technical_support': '技术支持',
    'faq': '常见问题',
    'user_manual': '用户手册',
    'business_process': '业务流程',
    'training_material': '培训材料',
    'best_practices': '最佳实践',
    'safety_compliance': '安全合规',
    'api_documentation': 'API文档',
    'troubleshooting': '故障排查',
    'configuration': '配置说明',
    'release_notes': '更新日志',
    'integration': '系统集成',
    'performance': '性能优化',
    'security': '安全策略',
    'data_management': '数据管理',
    'general_knowledge': '通用知识',
    'other': '其他',
    // 日常生活分类
    'health_care': '健康保健',
    'cooking_recipe': '烹饪食谱',
    'travel_guide': '旅游攻略',
    'education_learning': '教育学习',
    'financial_management': '理财投资',
    'lifestyle': '生活方式',
    'home_decoration': '家居装修',
    'parenting': '育儿知识',
    'fitness_sports': '健身运动',
    'entertainment': '娱乐资讯',
    'shopping_guide': '购物指南',
    'legal_advice': '法律常识',
    'vehicle_maintenance': '汽车保养',
    'pet_care': '宠物护理',
    'weather_info': '天气信息',
    'culture_history': '文化历史',
    'science_technology': '科学技术',
    'career_development': '职业发展',
    'relationship_social': '人际关系',
    'time_management': '时间管理',
    'emergency_firstaid': '急救知识'
  };
  return categoryMap[categoryName] || categoryName;
};

// 显示RAGflow同步对话框
const showRAGFlowSyncDialog = async () => {
  ragFlowSyncDialogVisible.value = true;
  await refreshRAGFlowKnowledgeBases();
};

// 刷新RAGflow知识库列表
const refreshRAGFlowKnowledgeBases = async () => {
  ragFlowLoading.value = true;
  try {
    const res = await ragFlowSyncApi.getRAGFlowKnowledgeBases();
    ragFlowKnowledgeBases.value = res.data?.result || [];
    
    if (ragFlowKnowledgeBases.value.length === 0) {
      ElMessage.warning('未找到RAGflow知识库,请检查RAGflow服务是否正常运行');
    }
  } catch (error: any) {
    console.error('获取RAGflow知识库列表失败:', error);
    ElMessage.error(error?.message || '获取知识库列表失败，请检查RAGflow服务');
    ragFlowKnowledgeBases.value = [];
  } finally {
    ragFlowLoading.value = false;
  }
};

// 同步单个知识库
const syncSingleKnowledgeBase = async (kbId: string) => {
  await ElMessageBox.confirm(
    `确认同步知识库"${ragFlowKnowledgeBases.value.find(kb => kb.id === kbId)?.name || kbId}"吗？`,
    '确认同步',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  );

  ragFlowSyncing.value = true;
  try {
    const res = await ragFlowSyncApi.syncFromRAGFlow({ kbId });
    const result = res.data?.result || null;
    
    if (result && result.failed === 0) {
      ElMessage.success(`同步成功！共处理 ${result.total} 条知识`);
    } else if (result) {
      ElMessage.warning(`同步完成，${result.success} 条成功，${result.failed} 条失败`);
    }
    
    // 刷新本地知识库列表
    await handleQuery();
  } catch (error: any) {
    console.error('同步失败:', error);
    ElMessage.error(error?.message || '同步失败，请重试');
  } finally {
    ragFlowSyncing.value = false;
  }
};

// 同步所有知识库
const syncAllKnowledgeBases = async () => {
  await ElMessageBox.confirm(
    `确认同步所有知识库吗？共 ${ragFlowKnowledgeBases.value.length} 个知识库，可能需要较长时间。`,
    '确认同步',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  );

  ragFlowSyncing.value = true;
  try {
    const res = await ragFlowSyncApi.syncFromRAGFlow({});
    const result = res.data?.result || null;
    
    syncResult.value = result;
    syncResultVisible.value = true;
    
    if (result && result.failed === 0) {
      ElMessage.success(`同步成功！共处理 ${result.total} 条知识`);
    } else if (result) {
      ElMessage.warning(`同步完成，${result.success} 条成功，${result.failed} 条失败`);
    }
    
    // 刷新本地知识库列表
    await handleQuery();
  } catch (error: any) {
    console.error('同步失败:', error);
    ElMessage.error(error?.message || '同步失败，请重试');
  } finally {
    ragFlowSyncing.value = false;
  }
};

// 跳转到个人记忆管理页面
const goToPersonalMemory = () => {
  router.push('/wms/personalMemory');
};

onMounted(() => {
  handleQuery();
  getCategories();
});

// ===== Qdrant 检查相关 =====
const checkQdrantCount = async () => {
  qdrantLoading.value = true;
  try {
    const res = await knowledgeBaseApi.getQdrantPointsCount({ exact: true });
    const count = extractCount(res.data);
    ElMessage.success(`Qdrant 向量数量：${count}`);
  } catch (e: any) {
    ElMessage.error(e?.message || '获取向量数量失败');
  } finally {
    qdrantLoading.value = false;
  }
};

const showQdrantCollectionInfo = async () => {
  qdrantLoading.value = true;
  try {
    const res = await knowledgeBaseApi.getQdrantCollectionInfo();
    qdrantCollectionJson.value = JSON.stringify(res.data?.result ?? res.data, null, 2);
    qdrantCollectionDialogVisible.value = true;
  } catch (e: any) {
    ElMessage.error(e?.message || '获取集合信息失败');
  } finally {
    qdrantLoading.value = false;
  }
};

const showQdrantSamples = async () => {
  qdrantLoading.value = true;
  try {
    const res = await knowledgeBaseApi.scrollQdrantPoints({ limit: 5 });
    qdrantSamplesJson.value = JSON.stringify(res.data?.result ?? res.data, null, 2);
    qdrantSamplesDialogVisible.value = true;
  } catch (e: any) {
    ElMessage.error(e?.message || '获取示例失败');
  } finally {
    qdrantLoading.value = false;
  }
};

// 提取 count 的通用方法，兼容不同返回结构
function extractCount(payload: any): number {
  const tryParse = (x: any) => {
    if (typeof x === 'string') {
      try { return JSON.parse(x); } catch { return x; }
    }
    return x;
  };
  const unwrap = (x: any) => {
    const p = tryParse(x);
    const r = tryParse(p?.result);
    const d = tryParse(p?.data);
    return r ?? d ?? p;
  };
  let cur: any = unwrap(payload);
  if (typeof cur === 'number') return cur;
  if (typeof cur?.count === 'number') return cur.count;
  if (typeof cur?.points_count === 'number') return cur.points_count;
  if (typeof cur?.result === 'number') return cur.result;
  if (typeof cur?.result?.count === 'number') return cur.result.count;
  return 0;
}
</script>

<style scoped>
.knowledge-base-container {
  padding: 10px;
}

.knowledge-detail {
  max-height: 600px;
  overflow-y: auto;
}

.knowledge-content {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  white-space: pre-wrap;
  line-height: 1.6;
}
</style>
